//
//  SCPhotoPreviewPresentAnimationTransition.m
//  PhotoAlbum
//
//  Created by Chao Sheng on 2021/12/10.
//

#import "SCPhotoPreviewPresentAnimationTransition.h"

@interface SCPhotoPreviewPresentAnimationTransition ();

@property (nonatomic, assign) SCTransitionType type;

@property (nonatomic, strong) SCPhotoView *photoView;

@end

@implementation SCPhotoPreviewPresentAnimationTransition

- (instancetype)initWithPresentTransitionType:(SCTransitionType)type photoView:(SCPhotoView *)photoView {
    if(self=[super init]) {
        self.type = type;
        self.photoView = photoView;
    }
    return self;;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    switch (self.type) {
        case SCTransitionPresentType:
            if (self.photoView) {
                [self presentAnimation:transitionContext photoView:self.photoView];
            } else {
                [self presentAnimation:transitionContext];
            }
            break;
        case SCTransitionDismissType:
            if (self.photoView) {
                [self dismissAnimation:transitionContext photoView:self.photoView];
            } else {
                [self dismissAnimation:transitionContext];
            }
            break;
        default:
            [transitionContext completeTransition:YES];
            break;
    }
}

- (NSTimeInterval)transitionDuration:(nullable id<UIViewControllerContextTransitioning>)transitionContext {
    if (self.type == SCTransitionPresentType) {
        return 0.45;
    } else {
        return 0.2;
    }
}

#pragma mark - photoView存在
- (void)presentAnimation:(id<UIViewControllerContextTransitioning>)transitionContext photoView:(SCPhotoView*)photoView {
    UINavigationController *toVC = (UINavigationController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UICollectionView *collectionView = (UICollectionView *)photoView.collectionView;
    
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    if ([fromVC isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)fromVC;
        fromVC = nav.viewControllers.firstObject;
    }
    
    SCPhotoSubCell *cell = (SCPhotoSubCell*)[collectionView cellForItemAtIndexPath:photoView.currentIndexPath];
    [self presentAnim:transitionContext Image:cell.imageView.image Model:cell.photoModel FromVC:fromVC ToVC:toVC cell:cell PhotoView:photoView];
}

- (void)presentAnim:(id<UIViewControllerContextTransitioning>)transitionContext Image:(UIImage *)image Model:(SCPhotoModel *)model FromVC:(UIViewController *)fromVC ToVC:(UINavigationController *)toVC cell:(SCPhotoSubCell *)cell PhotoView:(SCPhotoView*)photoView {
    
    SCPhotoAlbumPreviewViewController *toSubVC = toVC.viewControllers.firstObject;
    
    UIView *containerView = [transitionContext containerView];
    [containerView addSubview:toVC.view];
    
    UIImageView *tempView = [[UIImageView alloc] initWithImage:image];
    UIView *tempBgView = [[UIView alloc] initWithFrame:containerView.bounds];
    tempView.clipsToBounds = YES;
    tempView.contentMode = UIViewContentModeScaleAspectFill;
    tempView.frame = [cell.imageView convertRect:cell.imageView.bounds toView:containerView];
    [tempBgView addSubview:tempView];
    
    [fromVC.view insertSubview:tempBgView belowSubview:photoView];
    UIColor *oldColor = fromVC.view.backgroundColor;
    fromVC.view.backgroundColor = [UIColor whiteColor];
    
    toSubVC.collectionView.hidden = YES;
    toSubVC.view.backgroundColor = [UIColor clearColor];
    toSubVC.bottomView.alpha = 0;
    photoView.hidden = YES;
    
    CGFloat width = sc_WIDTH;
    CGFloat height = sc_HEIGHT-sc_BOTTOMPADDING_HEIGHT-sc_NAVIGATION_HEIGHT;
    CGFloat imgWidth = model.imgSize.width?model.imgSize.width:image.size.width;
    CGFloat imgHeight = model.imgSize.height?model.imgSize.height:image.size.height;
    CGFloat w;
    CGFloat h;
    
    imgHeight = width / imgWidth * imgHeight;
    if (imgHeight > height) {
        w = height / (model.imgSize.height?model.imgSize.height:image.size.height) * imgWidth;
        h = height;
    }else {
        w = width;
        h = imgHeight;
    }
    imgWidth = w ;
    imgHeight = h ;
    
    toSubVC.navigationController.navigationBar.userInteractionEnabled = NO;
    
    for (UIView *view in fromVC.view.subviews) {
        if (view != tempBgView) {
            view.hidden = YES;
        }
    }
    
    //考虑fromVC的NavigationBar显示时，先隐藏再执行动画
    BOOL hidden = fromVC.navigationController.navigationBarHidden;
    [fromVC.navigationController setNavigationBarHidden:YES];
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0 usingSpringWithDamping:0.75f initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        tempView.frame = CGRectMake((width - imgWidth) / 2, (height + sc_NAVIGATION_HEIGHT - imgHeight) / 2, imgWidth, imgHeight);
        toSubVC.bottomView.alpha = 1;

    } completion:^(BOOL finished) {
        
        for (UIView *view in fromVC.view.subviews) {
            view.hidden = NO;
        }
        
        toSubVC.view.backgroundColor = [UIColor whiteColor];
        toSubVC.collectionView.hidden = NO;
        [tempBgView removeFromSuperview];
        [tempView removeFromSuperview];
        toSubVC.navigationController.navigationBar.userInteractionEnabled = YES;
        [fromVC.navigationController setNavigationBarHidden:hidden];
        fromVC.view.backgroundColor = oldColor;
        photoView.hidden = NO;
        
        
        [transitionContext completeTransition:YES];
    
    }];
}

- (void)dismissAnimation:(id<UIViewControllerContextTransitioning>)transitionContext photoView:(SCPhotoView*)photoView {
    UINavigationController *fromVC = (UINavigationController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    SCPhotoAlbumPreviewViewController *fromSubVC = fromVC.viewControllers.firstObject;
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    SCPhotoModel *model = [fromSubVC.photoList objectAtIndex:fromSubVC.currentModelIndex];
    SCPhotoPreviewViewCell *fromCell = [fromSubVC currentPhotoCell:model];
    UIImageView *tempView = [[UIImageView alloc] initWithImage:fromCell.imageView.image];
    tempView.clipsToBounds = YES;
    tempView.contentMode = UIViewContentModeScaleAspectFill;
    tempView.backgroundColor = [UIColor clearColor];
    UIView *containerView = [transitionContext containerView];
    tempView.frame = [fromCell.imageView convertRect:fromCell.imageView.bounds toView:containerView];
  
    if ([toVC isKindOfClass:[UINavigationController class]]) {
        [containerView addSubview:toVC.view];
    }
//    [containerView addSubview:fromVC.view];
//    [fromSubVC.view insertSubview:tempView atIndex:0];
    if ([toVC isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tab = (UITabBarController*)toVC;
        [tab.tabBar setHidden:YES];
        [containerView addSubview:tab.view];
    }
    
    [containerView addSubview:tempView];
    
    UICollectionView *collectionView = (UICollectionView *)photoView.collectionView;
    SCPhotoSubCell *toCell = (SCPhotoSubCell*)[collectionView cellForItemAtIndexPath:[photoView currentIndexPathInModel:model]];
    
    CGRect rect = [toCell.imageView convertRect:toCell.imageView.bounds toView:containerView];
    fromSubVC.view.backgroundColor = [UIColor clearColor];
    fromSubVC.navigationController.navigationBar.alpha = 1;
    fromSubVC.collectionView.hidden = YES;
    fromSubVC.bottomView.hidden = YES;
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext]  animations:^{
        tempView.frame = rect;
        fromSubVC.navigationController.navigationBar.alpha = 0;
    }completion:^(BOOL finished) {
        [tempView removeFromSuperview];
        
        [transitionContext completeTransition:YES];
    }];
    
}

#pragma mark - photoView不存在
- (void)presentAnimation:(id<UIViewControllerContextTransitioning>)transitionContext {
    UINavigationController *fromVC = (UINavigationController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UINavigationController *toVC = (UINavigationController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

    SCPhotoAlbumPreviewViewController *toSubVC = toVC.viewControllers.firstObject;
    SCPhotoModel *model = [toSubVC.photoList objectAtIndex:toSubVC.currentModelIndex];
    
    if (model.highQualityImage) {
        [self presentAnim:transitionContext image:model.highQualityImage model:model fromVC:fromVC toVC:toVC];
    } else {
        __weak typeof(self) weakSelf = self;
        [SCPhotoTools getPhotoForPHAsset:model.asset size:CGSizeMake(model.imgSize.width, model.imgSize.height) completion:^(UIImage * _Nonnull image, PHAsset *asset) {
            if (model.asset == asset) {
                [weakSelf presentAnim:transitionContext image:image model:model fromVC:fromVC toVC:toVC];
            }
        }];
    }
}

- (void)presentAnim:(id<UIViewControllerContextTransitioning>)transitionContext image:(UIImage*)image model:(SCPhotoModel*)model fromVC:(UINavigationController*)fromVC toVC:(UINavigationController*)toVC {
    model.highQualityImage = image;
    
    UIView *containerView = [transitionContext containerView];
    UIImageView *tempView = [[UIImageView alloc] initWithImage:image];
    UIView *tempBgView = [[UIView alloc] initWithFrame:containerView.bounds];
    tempBgView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0];
    tempView.clipsToBounds = YES;
    tempView.contentMode = UIViewContentModeScaleAspectFill;
    
    SCPhotoAlbumListViewController *fromSubVC = fromVC.viewControllers.firstObject;
    SCPhotoAlbumPreviewViewController *toSubVC = toVC.viewControllers.firstObject;
    
    CGFloat width = sc_WIDTH;
    CGFloat height = sc_HEIGHT-sc_BOTTOMPADDING_HEIGHT-sc_NAVIGATION_HEIGHT;
    CGFloat imgWidth = model.imgSize.width;
    CGFloat imgHeight = model.imgSize.height;
    CGFloat w;
    CGFloat h;
    
    imgHeight = width / imgWidth * imgHeight;
    if (imgHeight > height) {
        w = height / model.imgSize.height * imgWidth;
        h = height;
    }else {
        w = width;
        h = imgHeight;
    }
    imgWidth = w ;
    imgHeight = h ;
    
    SCPhotoCell *fromCell = [fromSubVC currentPhotoCell:model];
    if (fromCell) {
        tempView.frame = [fromCell.photoImageView convertRect:fromCell.photoImageView.bounds toView: containerView];
    }else {
        tempView.center = CGPointMake(width / 2, height / 2);
    }
    
    [tempBgView addSubview:tempView];
    [fromSubVC.view insertSubview:tempBgView belowSubview:fromSubVC.bottomView];
    [containerView addSubview:fromVC.view];
    [containerView addSubview:toVC.view];
    toSubVC.collectionView.hidden = YES;
    toSubVC.view.backgroundColor = [UIColor clearColor];
    toSubVC.bottomView.alpha = 0;
    fromCell.hidden = YES;
    
    // 弹簧动画，参数分别为：时长，延时，弹性（越小弹性越大），初始速度
    toSubVC.navigationController.navigationBar.userInteractionEnabled = NO;
    UIViewAnimationOptions option = UIViewAnimationOptionCurveEaseOut;
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0 usingSpringWithDamping:0.8f initialSpringVelocity:0 options:option animations:^{
        tempView.frame = CGRectMake((width - imgWidth) / 2, (height + sc_NAVIGATION_HEIGHT - imgHeight) / 2, imgWidth, imgHeight);
        tempBgView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:1];
        toSubVC.bottomView.alpha = 1;
        
    } completion:^(BOOL finished) {
        fromCell.hidden = NO;
        
        toSubVC.view.backgroundColor = [UIColor whiteColor];
        toSubVC.collectionView.hidden = NO;
        [tempBgView removeFromSuperview];
        [tempView removeFromSuperview];
        toSubVC.navigationController.navigationBar.userInteractionEnabled = YES;
        [transitionContext completeTransition:YES];
    }];
}

- (void)dismissAnimation:(id<UIViewControllerContextTransitioning>)transitionContext {
    
    UINavigationController *fromVC = (UINavigationController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UINavigationController *toVC = (UINavigationController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    SCPhotoAlbumPreviewViewController *fromSubVC = fromVC.viewControllers.firstObject;
    SCPhotoAlbumListViewController *toSubVC = toVC.viewControllers.firstObject;
    
    SCPhotoModel *model = [fromSubVC.photoList objectAtIndex:fromSubVC.currentModelIndex];
    
    SCPhotoPreviewViewCell *fromCell = [fromSubVC currentPhotoCell:model];
    SCPhotoCell *toCell = [toSubVC currentPhotoCell:model];
    
    UIImageView *tempView = [[UIImageView alloc] initWithImage:fromCell.imageView.image];
    tempView.clipsToBounds = YES;
    tempView.contentMode = UIViewContentModeScaleAspectFill;
    BOOL contains = YES;
    if (!toCell) {
        contains = [toSubVC scrollToModel:model];
        toCell = [toSubVC currentPhotoCell:model];
    }
    
    UIView *containerView = [transitionContext containerView];
    UIView *tempBgView = [[UIView alloc] initWithFrame:containerView.bounds];
    [tempBgView addSubview:tempView];
    [containerView addSubview:toVC.view];
    [containerView addSubview:fromVC.view];

    [toSubVC.view insertSubview:tempBgView belowSubview:toSubVC.bottomView];
    tempBgView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:1];
    toSubVC.navigationController.navigationBar.userInteractionEnabled = NO;
    
    fromSubVC.collectionView.hidden = YES;
    toCell.alpha = 0;
    fromSubVC.view.backgroundColor = [UIColor clearColor];
    
    tempView.frame = [fromCell.imageView convertRect:fromCell.imageView.bounds toView:containerView];
    
    CGRect rect = [toCell.photoImageView convertRect:toCell.photoImageView.bounds toView: containerView];
    if (toCell) {
        [toSubVC scrollToPoint:toCell rect:rect];
    }

    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        
        if (!contains || !toCell) {
            tempView.transform = CGAffineTransformMakeScale(0.3, 0.3);
            tempView.alpha = 0;
        }else {
            tempView.frame = [toCell.photoImageView convertRect:toCell.photoImageView.bounds toView: containerView];
        }

        fromSubVC.view.backgroundColor = [UIColor clearColor];
        fromSubVC.bottomView.alpha = 0;
        fromSubVC.navigationController.navigationBar.alpha = 0;

        if (!fromSubVC.bottomView.userInteractionEnabled) {
            tempBgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        } else {
            tempBgView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0];
        }
        
        toCell.alpha = 1;
        
    } completion:^(BOOL finished) {
        
        toSubVC.navigationController.navigationBar.userInteractionEnabled = YES;
        //toCell.hidden = NO;
        [tempBgView removeFromSuperview];
        [tempView removeFromSuperview];
        
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
        
    }];

    
}


@end
